<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>EAN 13 :: Check Digit</title>
<link href="styles/style.css" rel="stylesheet" type="text/css">
</head>

<body>
<?php
require ("../db.php");

$contador=0;
$consulta = "SELECT TOP 5000 * FROM tbl_TarjetasEmision WHERE checkdigit is null;";
$res_consulta=mssql_query($consulta);
$faltantes = mssql_num_rows($res_consulta);
while($row_consulta=mssql_fetch_assoc($res_consulta)) {
    $contador++;
    $codigo=$row_consulta['code'];
    echo $contador."-> codigo:".$codigo."|";
    //$odds=substr($codigo,12,1)+substr($codigo,10,1)+substr($codigo,8,1)+substr($codigo,6,1)+substr($codigo,4,1)+substr($codigo,2,1);
    //$even=substr($codigo,11,1)+substr($codigo,9,1)+substr($codigo,7,1)+substr($codigo,5,1)+substr($codigo,3,1)+substr($codigo,1,1);
    $odds=substr($codigo,11,1)+substr($codigo,9,1)+substr($codigo,7,1)+substr($codigo,5,1)+substr($codigo,3,1)+substr($codigo,1,1);
    $even=substr($codigo,10,1)+substr($codigo,8,1)+substr($codigo,6,1)+substr($codigo,4,1)+substr($codigo,2,1)+substr($codigo,0,1);
    $sumaoddeven = ($odds * 3) + $even;
    $entre10 = ($sumaoddeven / 10);
	$check = $sumaoddeven - (floor($entre10)*10);
    //$check = 10 - ($sumaoddeven -(floor($entre10)*10));
    $checkdigit = abs($check - 10);
	if (strlen($checkdigit) > 1) {  $checkdigit = substr($checkdigit, strlen($checkdigit)-1, 1); }
    //echo "suma:".$sumaoddeven."|";
    //echo "mod:".$check."|";	
	echo "checkdigit:".$checkdigit."|";
	echo "tarjeta:".$codigo.$checkdigit."|";
	echo "<br>";
    $update="UPDATE tbl_TarjetasEmision
            SET checkdigit = '".$checkdigit."', tarjeta = '".$codigo.$checkdigit."'
            WHERE (code = '".$codigo."')";
    mssql_query($update);
}

if($faltantes > 0) {
  	echo "<meta http-equiv='REFRESH' content='0;url=setTarjetasEAN13complete.php'>";
}
mssql_close();
?>
FINISHED!
</body>
</html>